# This file replicate Figure 1 in appendix and table 2 in appendix

library(tidyverse)
library(gridExtra)

survey <- haven::read_dta("survey_data.dta")
lab <- haven::read_dta("psm_lab_prep.dta")

lab <- lab %>% filter(period == 1)
survey <- survey %>% filter(q == "Q19")

###########################
# PSM
###########################

survey_psm <- select(survey, psm = psm_s01); survey_psm$Mode <- "Survey Experiment"
lab_psm <- select(lab, psm = psm_s01); lab_psm$Mode <- "Laboratory Experiment"

psm <- rbind(survey_psm, lab_psm)

psm_dens <- ggplot(psm, aes(x = psm)) + 
geom_density(alpha = 0.7, color = NA, fill = "steelblue") +
theme_bw(base_size = 22) +
facet_wrap(~ Mode) +
guides(fill = FALSE) +
xlab("PSM Score") +
ylab("Density")

psm_dens

###########################
# RISK
###########################

survey_risk <- select(survey, risk = risk_beruf_r); survey_risk$Mode <- "Survey Experiment"
lab_risk <- select(lab, risk = risk_beruf_r); lab_risk$Mode <- "Laboratory Experiment"

risk <- rbind(survey_risk, lab_risk)

risk_dens <- ggplot(risk, aes(x = risk)) + 
  geom_bar(alpha = 0.7, color = NA, fill = "steelblue") +
  theme_bw(base_size = 22) +
  facet_wrap(~ Mode, scales = "free_y") +
  guides(fill = FALSE) +
  xlab("Risk Aversion") +
  ylab("Frequency") +
  scale_x_continuous(breaks = c(0, 0.5, 1))

risk_dens

full_plot <- gridExtra::grid.arrange(psm_dens, risk_dens, nrow = 2)

ggsave(full_plot, file = "densities_appendix.pdf", width = 15, height = 10)
ggsave(full_plot, file = "densities_appendix.jpeg",
       width = 15, height = 10, dpi = 666)


####################################
# Descriptives
####################################

survey$od <- as.numeric(survey$od ==2)
svy <- dplyr::select(survey, psm = psm_s01, risk = risk_beruf_r, od = od, testq = brain, age = age, female = female)
lb <- dplyr::select(lab, psm = psm_s01, risk = risk_beruf_r, testq = brain, age = age, female = female)
svy$Type <- "Survey"
lb$Type <- "Lab"

svy_sum <- svy %>% summarise(N = n(), MinPSM = min(psm), MaxPSM = max(psm), AvePSM = mean(psm), MinRisk = min(risk), MaxRisk = max(risk), AveRisk = mean(risk), od = mean(od), testq = mean(testq), MinAge = min(age), MeanAge = mean(age), MaxAge = max(age), female = mean(female))
lab_sum <- lb %>% summarise(N = n(), MinPSM = min(psm), MaxPSM = max(psm), AvePSM = mean(psm), MinRisk = min(risk), MaxRisk = max(risk), AveRisk = mean(risk), testq = mean(testq), MinAge = min(age), MeanAge = mean(age), MaxAge = max(age), female = mean(female))

summ <- bind_rows(svy_sum, lab_sum)

tab <- xtable::xtable(summ, digits = 2)

xtable::print.xtable(tab, include.rownames = F, type = "html",
                     file = "descriptive_lab_survey.html")
